package com.sms.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jxl.write.WriteException;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sms.client.MeterService;
import com.sms.shared.ACReadingDTO;
import com.sms.shared.DCReadingDTO;
import com.sms.shared.Equipment;
import com.sms.shared.EquipmentDTO;
import com.sms.shared.EquipmentReading;
import com.sms.shared.ParameterDTO;
import com.sms.shared.PartySiteDTO;
import com.sms.shared.PartySiteRelation;
import com.sms.shared.ReadingDTO;
import com.sms.shared.ReportBean;
import com.sms.shared.Site;

public class MeterServiceImpl extends RemoteServiceServlet implements MeterService {

	public List<ArrayList> getSiteList(Long partyId) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List dataList = new ArrayList();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(PartySiteRelation.class, "PR");
			criteria.createAlias("PR.party", "P");
			criteria.createAlias("PR.site", "S");
			criteria.createAlias("S.equipments", "E");
			if (partyId != null)
				criteria.add(Restrictions.eq("P.id", partyId));
			criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("S.id"), "siteId").add(Projections.property("E.displayGroupNo"), "siteGroupNumber").add(Projections.property("S.location"), "location").add(Projections.property("P.name"), "customerName")));
			List<PartySiteDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(PartySiteDTO.class)).list();
			tx.commit();
			if(list == null)
				return dataList;
			for (PartySiteDTO partyMeterDTO : list) {
				List dataValueList = new ArrayList();
				dataValueList.add(partyMeterDTO.getSiteId());
				dataValueList.add(partyMeterDTO.getSiteGroupNumber());
				dataValueList.add(partyMeterDTO.getLocation());
				dataValueList.add(partyMeterDTO.getCustomerName());
				dataList.add(dataValueList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataList;
	}

	public Map getMapInfo(Long partyId) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		Map dataMap = new HashMap();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(PartySiteRelation.class, "PR");

			criteria.createAlias("PR.site", "S");
			criteria.createAlias("S.equipments", "E");
			if (partyId != null) {
				criteria.createAlias("PR.party", "P");
				criteria.add(Restrictions.eq("P.id", partyId));
			}
			criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("S.mapAddress"), "mapAddress").add(Projections.property("E.displayGroupNo"), "siteGroupNumber")));
			List<PartySiteDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(PartySiteDTO.class)).list();
			tx.commit();
			for (PartySiteDTO partyMeterDTO : list) {
				List dataList = null;
				if (!dataMap.containsKey(partyMeterDTO.getMapAddress())) {
					dataList = new ArrayList();
				} else
					dataList = (List) dataMap.get(partyMeterDTO.getMapAddress());
				dataList.add(partyMeterDTO.getSiteGroupNumber());

				dataMap.put(partyMeterDTO.getMapAddress(), dataList);

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataMap;
	}

	public Map getDashBoardData(Long siteId, String displayGroupNo, String equipmentType, String vType, Date startDate, Date endDate, boolean isDGConfigured) {
		if (equipmentType.equalsIgnoreCase("D G"))
			equipmentType = "Diesel Generator";
		Map chartMap = null;
		if(equipmentType.contains(",")){
			chartMap = new LinkedHashMap();
			if(equipmentType.contains("Panel"))
				chartMap.put("Panel", getDataMapByGroupNo(siteId, displayGroupNo, "Panel", vType, startDate, endDate, isDGConfigured, true)) ;
			if(equipmentType.contains("Inverter"))
				chartMap.put("Inverter",getDataMapByGroupNo(siteId, displayGroupNo, "Inverter", vType, startDate, endDate, isDGConfigured, true));
			
//			chartMap = getDataMapByGroupNo(siteId, displayGroupNo, "Battery", vType, startDate, endDate, isDGConfigured, true);
			if(equipmentType.contains("Utility"))
				chartMap.put("Utility", getDataMapByGroupNo(siteId, displayGroupNo, "Utility", vType, startDate, endDate, isDGConfigured, true));
			if(equipmentType.contains("Diesel Generator"))
				chartMap.put("Diesel Generator",getDataMapByGroupNo(siteId, displayGroupNo, "Diesel Generator", vType, startDate, endDate, isDGConfigured, true));

		}else{
			if(!equipmentType.equalsIgnoreCase("All")){
				chartMap = getDataMapByGroupNo(siteId, displayGroupNo, equipmentType, vType, startDate, endDate, isDGConfigured, true);
			}else{
				chartMap = new LinkedHashMap();
				
				chartMap.put("Panel", getDataMapByGroupNo(siteId, displayGroupNo, "Panel", vType, startDate, endDate, isDGConfigured, true)) ;
				
				chartMap.put("Inverter",getDataMapByGroupNo(siteId, displayGroupNo, "Inverter", vType, startDate, endDate, isDGConfigured, true));
				
//				chartMap = getDataMapByGroupNo(siteId, displayGroupNo, "Battery", vType, startDate, endDate, isDGConfigured, true);
				
				chartMap.put("Utility", getDataMapByGroupNo(siteId, displayGroupNo, "Utility", vType, startDate, endDate, isDGConfigured, true));
				if(isDGConfigured)
					chartMap.put("Diesel Generator",getDataMapByGroupNo(siteId, displayGroupNo, "Diesel Generator", vType, startDate, endDate, isDGConfigured, true));
			}
		}
		
		// mainMap.put("ChartData", chartMap);
		return chartMap;
	}

	public List getReportData(Long siteId, String displayGroupNo, String vType, Date startDate, Date endDate, boolean isDGConfigured) {
		List dataList = new ArrayList();
		List headingList = new ArrayList();
		if (vType.equalsIgnoreCase("Hourly"))
			headingList.add("Hour");
		else if (vType.equalsIgnoreCase("Daily"))
			headingList.add("Date");
		else if (vType.equalsIgnoreCase("Monthly"))
			headingList.add("Month");
		else if (vType.equalsIgnoreCase("Yearly"))
			headingList.add("Year");
		else
			headingList.add("Log Date");
		// System.err.println("getReport Data : "+ vType);
		if (vType.equalsIgnoreCase("DC Log")) {
			headingList.add("Log Time");
			headingList.add("PV Voltage (V)");
			headingList.add("PV Current (Amps)");
			headingList.add("PV Energy (kWh)");
			headingList.add("Battery Voltage (V)");
			headingList.add("Inverter Voltage (V)");
			headingList.add("Inverter Current (Amps)");
			headingList.add("Inverter Energy (kWh)");
		} else if (vType.equalsIgnoreCase("AC Log")) {
			headingList.add("Log Time");
			headingList.add("Phase 1 Voltage (V)");
			headingList.add("Phase 2 Voltage (V)");
			headingList.add("Phase 3 Voltage (V)");
			headingList.add("Phase 1 Current (Amps)");
			headingList.add("Phase 2 Current (Amps)");
			headingList.add("Phase 3 Current (Amps)");
			headingList.add("EB/DG");
			headingList.add("Energy(kWh)");

		}else if (vType.equalsIgnoreCase("DC - AC Log")) {
			headingList.add("Log Time");
			headingList.add("PV Voltage (V)");
			headingList.add("PV Current (Amps)");
			headingList.add("PV Energy (kWh)");
			headingList.add("Battery Voltage (V)");
			headingList.add("Inverter Voltage (V)");
			headingList.add("Inverter Current (Amps)");
			headingList.add("Inverter Energy (kWh)");
			headingList.add("Phase 1 Voltage (V)");
			headingList.add("Phase 2 Voltage (V)");
			headingList.add("Phase 3 Voltage (V)");
			headingList.add("Phase 1 Current (Amps)");
			headingList.add("Phase 2 Current (Amps)");
			headingList.add("Phase 3 Current (Amps)");
			headingList.add("EB/DG");
			headingList.add("Energy(kWh)");
		} 
		else {
			headingList.add("Solar Genaration (Kwh)");
			headingList.add("Facility Consumption (Kwh)");
			headingList.add("Utility Consumption (Kwh)");
			// if(isDGConfigured)
			// headingList.add("DG (Kwh)");

		}
		dataList.add(headingList);

		if (!vType.contains("Log")) {
			Map panelMap = getDataMapByGroupNo(siteId, displayGroupNo, "Panel", vType, startDate, endDate, isDGConfigured, false);
			Map inverterMap = getDataMapByGroupNo(siteId, displayGroupNo, "Inverter", vType, startDate, endDate, isDGConfigured, false);
			Map utilityMap = getDataMapByGroupNo(siteId, displayGroupNo, "Utility", vType, startDate, endDate, isDGConfigured, false);
			// Map dgMap = null;
			// if (isDGConfigured)
			// dgMap = getDataMapByGroupNo(siteId, displayGroupNo,
			// "Diesel Generator", vType, startDate, endDate, isDGConfigured,
			// false);

			Map valueMap = new LinkedHashMap();

			Set set = panelMap.entrySet();
			Iterator i = set.iterator();
			while (i.hasNext()) {
				Map.Entry me = (Map.Entry) i.next();
				String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
				if (me.getValue() != null) {
					ArrayList dataValueList = (ArrayList) me.getValue();
					Double value = (Double) dataValueList.get(0);
					List valueList = null;
					if (valueMap.containsKey(key))
						valueList = (List) valueMap.get(key);
					else {
						valueList = new ArrayList();
						valueList.add(key);
					}
					valueList.add(value);
					valueMap.put(key, valueList);

				}
			}
			// System.err.println("panel: " + valueMap.toString());

			set = inverterMap.entrySet();
			i = set.iterator();
			while (i.hasNext()) {
				Map.Entry me = (Map.Entry) i.next();
				String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
				if (me.getValue() != null) {
					ArrayList dataValueList = (ArrayList) me.getValue();
					Double value = (Double) dataValueList.get(0);
					List valueList = null;
					if (valueMap.containsKey(key))
						valueList = (List) valueMap.get(key);
					else {
						valueList = new ArrayList();
						valueList.add(key);
					}
					valueList.add(value);
					valueMap.put(key, valueList);
				}
			}
			// System.err.println("inverterMap : " + valueMap.toString());

			set = utilityMap.entrySet();
			i = set.iterator();
			while (i.hasNext()) {
				Map.Entry me = (Map.Entry) i.next();
				String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
				if (me.getValue() != null) {

					ArrayList dataValueList = (ArrayList) me.getValue();
					Double value = (Double) dataValueList.get(0);
					List valueList = null;
					if (valueMap.containsKey(key))
						valueList = (List) valueMap.get(key);
					else {
						valueList = new ArrayList();
						valueList.add(key);
					}
					valueList.add(value);
					valueMap.put(key, valueList);
				}
			}
			// if (isDGConfigured) {
			// set = dgMap.entrySet();
			// i = set.iterator();
			// while (i.hasNext()) {
			// Map.Entry me = (Map.Entry) i.next();
			// String key = (me.getKey() instanceof String) ? (String)
			// me.getKey() : String.valueOf(me.getKey());
			// if (me.getValue() != null) {
			//
			// ArrayList dataValueList = (ArrayList) me.getValue();
			// Double value = (Double) dataValueList.get(0);
			// List valueList = null;
			// if (valueMap.containsKey(key))
			// valueList = (List) valueMap.get(key);
			// else {
			// valueList = new ArrayList();
			// valueList.add(key);
			// }
			// valueList.add(value);
			// valueMap.put(key, valueList);
			// }
			// }
			// //System.err.println("dg: " + valueMap.toString());
			// }

			Set valueSet = valueMap.entrySet();
			Iterator valueIterator = valueSet.iterator();
			while (valueIterator.hasNext()) {
				Map.Entry me = (Map.Entry) valueIterator.next();
				String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
				if (me.getValue() != null) {
					List dataValueList = (List) me.getValue();
					if (headingList.size() == dataValueList.size()) {
						dataList.add(dataValueList);
					} else {
						for (int index = dataValueList.size(); index < headingList.size(); index++) {
							dataValueList.add(0.0);
						}
						dataList.add(dataValueList);
					}

				}
			}

		} else if (vType.equalsIgnoreCase("DC Log")) {
			List<List> dcReadingList = getDCReadingList(displayGroupNo, startDate);
			for (List dataValueList : dcReadingList) {
				dataList.add(dataValueList);
			}

		} else if (vType.equalsIgnoreCase("AC Log")) {
			List<List> acReadingList = getACReadingList(displayGroupNo, startDate);
			for (List dataValueList : acReadingList) {
				dataList.add(dataValueList);
			}
		}else if (vType.equalsIgnoreCase("DC - AC Log")) {
			List<List> dcReadingList = getDCReadingList(displayGroupNo, startDate);
			List<List> acReadingList = getACReadingList(displayGroupNo, startDate);
			Map<String,List> acReadingMap  =  new HashMap<String,List>();
			for (List dataValueList : acReadingList) {
				acReadingMap.put((String)dataValueList.get(1),dataValueList);
			}
			
			for (List dataValueList : dcReadingList) {
				String dcLogTime = (String)dataValueList.get(1);
				List dcDataValueList = null;
				if(acReadingMap.containsKey(dcLogTime)){
					dcDataValueList = acReadingMap.get(dcLogTime);
					dcDataValueList.remove(0);
					dcDataValueList.remove(0);
				}else{
					dcDataValueList = new ArrayList();
					dcDataValueList.add(0.0);
					dcDataValueList.add(0.0);
					dcDataValueList.add(0.0);
					dcDataValueList.add(0.0);
					dcDataValueList.add(0.0);
					dcDataValueList.add(0.0);
					dcDataValueList.add("-");
					dcDataValueList.add(0.0);
				}
				dataValueList.addAll(dcDataValueList);
				dataList.add(dataValueList);
			}
		}
		
		return dataList;
	}

	private List<List> getDCReadingList(String displayGroupNo, Date readingDate) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		Map<Date, DCReadingDTO> dataMap = new LinkedHashMap<Date, DCReadingDTO>();
		Transaction tx = null;
		List dataList = new ArrayList();
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(EquipmentReading.class, "ER");
			criteria.createAlias("ER.equipment", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");

			String[] equipmentTypes = new String[] { "Panel", "Inverter", "Battery" };

			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.add(Restrictions.in("ET.name", equipmentTypes));

			Calendar endCalendar = Calendar.getInstance();
			endCalendar.setTime(readingDate);
			endCalendar.set(Calendar.HOUR_OF_DAY, 23);
			endCalendar.set(Calendar.MINUTE, 59);
			endCalendar.set(Calendar.SECOND, 00);
			endCalendar.set(Calendar.MILLISECOND, 0);

			Calendar startCalendar = Calendar.getInstance();
			startCalendar.setTime(readingDate);
			startCalendar.set(Calendar.HOUR_OF_DAY, 00);
			startCalendar.set(Calendar.MINUTE, 00);
			startCalendar.set(Calendar.SECOND, 00);
			startCalendar.set(Calendar.MILLISECOND, 0);

			criteria.add(Restrictions.ge("ER.readingDate", startCalendar.getTime()));
			criteria.add(Restrictions.le("ER.readingDate", endCalendar.getTime()));

			criteria.setProjection(Projections.projectionList().add(Projections.property("ER.readingDate"), "readingDate").add(Projections.property("ER.voltage"), "voltage").add(Projections.property("ER.current"), "current").add(Projections.property("ER.energy"), "energy").add(Projections.property("ER.phase"), "phase").add(Projections.property("ET.name"), "equipmentType")

			);
			criteria.addOrder(Order.asc("ER.readingDate"));
			criteria.addOrder(Order.asc("E.id"));
			List<ReadingDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(ReadingDTO.class)).list();
			DCReadingDTO dcReadingDTO = null;
			if (list != null) {
				for (ReadingDTO readingDTO : list) {

					if (dataMap.containsKey(readingDTO.getReadingDate())) {
						dcReadingDTO = dataMap.get(readingDTO.getReadingDate());
					} else {
						dcReadingDTO = new DCReadingDTO();
						dataMap.put(readingDTO.getReadingDate(), dcReadingDTO);
					}
					if (readingDTO.getEquipmentType().equalsIgnoreCase("Inverter")) {
						dcReadingDTO.setLogDate(new SimpleDateFormat("dd/MM/yyyy").format(readingDTO.getReadingDate()));
						dcReadingDTO.setLogTime(new SimpleDateFormat("HH:mm:ss").format(readingDTO.getReadingDate()));
						if (readingDTO.getVoltage() != null)
							dcReadingDTO.setLoadVoltage(readingDTO.getVoltage());
						else
							dcReadingDTO.setLoadVoltage(0.0);
						if (readingDTO.getCurrent() != null)
							dcReadingDTO.setLoadCurrent(readingDTO.getCurrent());
						else
							dcReadingDTO.setLoadCurrent(0.0);
						if (readingDTO.getEnergy() != null)
							dcReadingDTO.setLoadEnergy(readingDTO.getEnergy());
						else
							dcReadingDTO.setLoadEnergy(0.0);
					}
					if (readingDTO.getEquipmentType().equalsIgnoreCase("Panel")) {
						dcReadingDTO.setLogDate(new SimpleDateFormat("dd/MM/yyyy").format(readingDTO.getReadingDate()));
						dcReadingDTO.setLogTime(new SimpleDateFormat("HH:mm:ss").format(readingDTO.getReadingDate()));
						if (readingDTO.getVoltage() != null)
							dcReadingDTO.setPvVoltage(readingDTO.getVoltage());
						else
							dcReadingDTO.setPvVoltage(0.0);
						if (readingDTO.getCurrent() != null)
							dcReadingDTO.setPvCurrent(readingDTO.getCurrent());
						else
							dcReadingDTO.setPvCurrent(0.0);
						if (readingDTO.getEnergy() != null)
							dcReadingDTO.setPvEnergy(readingDTO.getEnergy());
						else
							dcReadingDTO.setPvEnergy(0.0);
					}

					if (readingDTO.getEquipmentType().equalsIgnoreCase("Battery")) {
						dcReadingDTO.setLogDate(new SimpleDateFormat("dd/MM/yyyy").format(readingDTO.getReadingDate()));
						dcReadingDTO.setLogTime(new SimpleDateFormat("HH:mm:ss").format(readingDTO.getReadingDate()));
						if (readingDTO.getVoltage() != null)
							dcReadingDTO.setbVoltage(readingDTO.getVoltage());
						else
							dcReadingDTO.setbVoltage(0.0);
					}

				}
				tx.commit();

				Iterator iter = dataMap.entrySet().iterator();

				while (iter.hasNext()) {
					Map.Entry<Date, DCReadingDTO> mEntry = (Map.Entry) iter.next();
					List dataValueList = new ArrayList();
					DCReadingDTO dcReading = mEntry.getValue();
					dataValueList.add(dcReading.getLogDate());
					dataValueList.add(dcReading.getLogTime());
					if (dcReading.getPvVoltage() != null)
						dataValueList.add(dcReading.getPvVoltage());
					else
						dataValueList.add(0.0);

					if (dcReading.getPvCurrent() != null)
						dataValueList.add(dcReading.getPvCurrent());
					else
						dataValueList.add(0.0);

					if (dcReading.getPvEnergy() != null)
						dataValueList.add(dcReading.getPvEnergy());
					else
						dataValueList.add(0.0);

					if (dcReading.getbVoltage() != null)
						dataValueList.add(dcReading.getbVoltage());
					else
						dataValueList.add(0.0);

					if (dcReading.getLoadVoltage() != null)
						dataValueList.add(dcReading.getLoadVoltage());
					else
						dataValueList.add(0.0);

					if (dcReading.getLoadCurrent() != null)
						dataValueList.add(dcReading.getLoadCurrent());
					else
						dataValueList.add(0.0);

					if (dcReading.getLoadEnergy() != null)
						dataValueList.add(dcReading.getLoadEnergy());
					else
						dataValueList.add(0.0);
					dataList.add(dataValueList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return dataList;
	}

	private List<List> getACReadingList(String displayGroupNo, Date readingDate) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		Map<Date, ACReadingDTO> dataMap = new LinkedHashMap<Date, ACReadingDTO>();
		List dataList = new ArrayList();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(EquipmentReading.class, "ER");
			criteria.createAlias("ER.equipment", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");

			String[] equipmentTypes = new String[] { "Utility", "Diesel Generator" };

			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.add(Restrictions.in("ET.name", equipmentTypes));

			Calendar endCalendar = Calendar.getInstance();
			endCalendar.setTime(readingDate);
			endCalendar.set(Calendar.HOUR_OF_DAY, 23);
			endCalendar.set(Calendar.MINUTE, 59);
			endCalendar.set(Calendar.SECOND, 00);
			endCalendar.set(Calendar.MILLISECOND, 0);

			Calendar startCalendar = Calendar.getInstance();
			startCalendar.setTime(readingDate);
			startCalendar.set(Calendar.HOUR_OF_DAY, 00);
			startCalendar.set(Calendar.MINUTE, 00);
			startCalendar.set(Calendar.SECOND, 00);
			startCalendar.set(Calendar.MILLISECOND, 0);

			criteria.add(Restrictions.ge("ER.readingDate", startCalendar.getTime()));
			criteria.add(Restrictions.le("ER.readingDate", endCalendar.getTime()));

			criteria.setProjection(Projections.projectionList().add(Projections.property("ER.readingDate"), "readingDate").add(Projections.property("ER.voltage"), "voltage").add(Projections.property("ER.current"), "current").add(Projections.property("ER.energy"), "energy").add(Projections.property("ER.phase"), "phase").add(Projections.property("ET.name"), "equipmentType")

			);
			criteria.addOrder(Order.asc("ER.readingDate"));
			criteria.addOrder(Order.asc("E.id"));
			List<ReadingDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(ReadingDTO.class)).list();
			ACReadingDTO acReadingDTO = null;
			if (list != null) {
				for (ReadingDTO readingDTO : list) {
					if (dataMap.containsKey(readingDTO.getReadingDate())) {
						acReadingDTO = dataMap.get(readingDTO.getReadingDate());
					} else {
						acReadingDTO = new ACReadingDTO();
						dataMap.put(readingDTO.getReadingDate(), acReadingDTO);
					}
					if (readingDTO.getEquipmentType().equalsIgnoreCase("Utility") && readingDTO.getPhase().equalsIgnoreCase("R")) {
						acReadingDTO.setLogDate(new SimpleDateFormat("dd/MM/yyyy").format(readingDTO.getReadingDate()));
						acReadingDTO.setLogTime(new SimpleDateFormat("HH:mm:ss").format(readingDTO.getReadingDate()));
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha1Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha1Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha1Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha1Current(0.0);
						if (readingDTO.getEnergy() != null)
							acReadingDTO.setEnergy(readingDTO.getEnergy());
						else
							acReadingDTO.setEnergy(0.0);
						acReadingDTO.setIsEBorDG("EB");
					}
					if (readingDTO.getEquipmentType().equalsIgnoreCase("Utility") && readingDTO.getPhase().equalsIgnoreCase("Y")) {
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha2Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha2Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha2Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha2Current(0.0);
					}

					if (readingDTO.getEquipmentType().equalsIgnoreCase("Utility") && readingDTO.getPhase().equalsIgnoreCase("B")) {
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha3Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha3Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha3Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha3Current(0.0);
						// dataMap.put(readingDTO.getReadingDate(),
						// acReadingDTO);
					}

					if (readingDTO.getEquipmentType().equalsIgnoreCase("Diesel Generator") && readingDTO.getPhase().equalsIgnoreCase("R")) {
						acReadingDTO.setLogDate(new SimpleDateFormat("dd/MM/yyyy").format(readingDTO.getReadingDate()));
						acReadingDTO.setLogTime(new SimpleDateFormat("HH:mm:ss").format(readingDTO.getReadingDate()));
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha1Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha1Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha1Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha1Current(0.0);
						if (readingDTO.getEnergy() != null)
							acReadingDTO.setEnergy(readingDTO.getEnergy());
						else
							acReadingDTO.setEnergy(0.0);
						acReadingDTO.setIsEBorDG("DG");
					}
					if (readingDTO.getEquipmentType().equalsIgnoreCase("Diesel Generator") && readingDTO.getPhase().equalsIgnoreCase("Y")) {
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha2Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha2Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha2Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha2Current(0.0);
					}

					if (readingDTO.getEquipmentType().equalsIgnoreCase("Diesel Generator") && readingDTO.getPhase().equalsIgnoreCase("B")) {
						if (readingDTO.getVoltage() != null)
							acReadingDTO.setPha3Voltage(readingDTO.getVoltage());
						else
							acReadingDTO.setPha3Voltage(0.0);
						if (readingDTO.getCurrent() != null)
							acReadingDTO.setPha3Current(readingDTO.getCurrent());
						else
							acReadingDTO.setPha3Current(0.0);
						// dataMap.put(readingDTO.getReadingDate(),
						// acReadingDTO);
					}
				}

				tx.commit();
				Iterator iter = dataMap.entrySet().iterator();

				while (iter.hasNext()) {
					Map.Entry<Date, ACReadingDTO> mEntry = (Map.Entry) iter.next();
					List dataValueList = new ArrayList();
					ACReadingDTO acReading = mEntry.getValue();
					dataValueList.add(acReading.getLogDate());
					dataValueList.add(acReading.getLogTime());
					if (acReading.getPha1Voltage() != null)
						dataValueList.add(acReading.getPha1Voltage());
					else
						dataValueList.add(0.0);

					if (acReading.getPha2Voltage() != null)
						dataValueList.add(acReading.getPha2Voltage());
					else
						dataValueList.add(0.0);

					if (acReading.getPha3Voltage() != null)
						dataValueList.add(acReading.getPha3Voltage());
					else
						dataValueList.add(0.0);

					if (acReading.getPha1Current() != null)
						dataValueList.add(acReading.getPha1Current());
					else
						dataValueList.add(0.0);

					if (acReading.getPha2Current() != null)
						dataValueList.add(acReading.getPha2Current());
					else
						dataValueList.add(0.0);

					if (acReading.getPha3Current() != null)
						dataValueList.add(acReading.getPha3Current());
					else
						dataValueList.add(0.0);

					dataValueList.add(acReading.getIsEBorDG());

					if (acReading.getEnergy() != null)
						dataValueList.add(acReading.getEnergy());
					else
						dataValueList.add(0.0);

					dataList.add(dataValueList);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataList;
	}

	public Map getGaugeMap(Long siteId, String displayGroupNo, String equipmentType, String phase) {
		Map mainMap = new HashMap();
		if (equipmentType.equalsIgnoreCase("D G"))
			equipmentType = "Diesel Generator";
		List<ParameterDTO> parameterlist = getGaugeConfiguration(siteId, displayGroupNo, equipmentType);
		Map<String, List<Integer>> confMap = new HashMap<String, List<Integer>>();
		for (ParameterDTO parameter : parameterlist) {
			List<Integer> dataValueList = new ArrayList<Integer>();
			dataValueList.add((int) Math.round(parameter.getStart()));
			dataValueList.add((int) Math.round(parameter.getEnd()));
			dataValueList.add((int) Math.round(parameter.getMinYellow()));
			dataValueList.add((int) Math.round(parameter.getMaxYellow()));
			dataValueList.add((int) Math.round(parameter.getMinGreen()));
			dataValueList.add((int) Math.round(parameter.getMaxGreen()));
			dataValueList.add((int) Math.round(parameter.getMinRed()));
			dataValueList.add((int) Math.round(parameter.getMaxRed()));
			confMap.put(parameter.getType(), dataValueList);
		}
		mainMap.put("GaugeConf", confMap);
		List<ReadingDTO> readingList = getGaugeReading(siteId, displayGroupNo, equipmentType, phase);
		if (readingList != null && readingList.size() > 0) {
			ReadingDTO readingDTO = readingList.get(0);
			List<Object> dataValueList = new ArrayList();
			dataValueList.add(new SimpleDateFormat("EEEE; MMM dd, yyyy hh:mm a").format(readingDTO.getReadingDate()));
			dataValueList.add(readingDTO.getVoltage());
			dataValueList.add(readingDTO.getCurrent());
			dataValueList.add(readingDTO.getEnergy());
			dataValueList.add(readingDTO.getPower());
			mainMap.put("GaugeValue", dataValueList);
		}
		return mainMap;
	}

	private Map getDataMapByGroupNo(Long siteId, String displayGroupNo, String equipmentType, String vType, Date startDate, Date endDate, boolean isDGConfigured, boolean isDashBoardData) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List<ReadingDTO> list = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(Site.class, "S");
			criteria.createAlias("S.equipments", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");
			criteria.createAlias("E.equipmentReadings", "ER");
			if (siteId != null)
				criteria.add(Restrictions.eq("S.id", siteId));
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.add(Restrictions.eq("ET.name", equipmentType));

			if (vType.equalsIgnoreCase("Hourly")) {

				Criteria maxReadingDateCriteria = session.createCriteria(Site.class, "S");
				maxReadingDateCriteria.createAlias("S.equipments", "E");
				maxReadingDateCriteria.createAlias("E.configuration", "C");
				maxReadingDateCriteria.createAlias("C.equipmentType", "ET");
				maxReadingDateCriteria.createAlias("E.equipmentReadings", "ER");
				if (siteId != null)
					maxReadingDateCriteria.add(Restrictions.eq("S.id", siteId));
				maxReadingDateCriteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
				maxReadingDateCriteria.add(Restrictions.eq("ET.name", equipmentType));
				maxReadingDateCriteria.setProjection(Projections.projectionList().add(Projections.min("ER.readingDate")).add(Projections.max("ER.readingDate")));
				List dateList = maxReadingDateCriteria.list();

				Iterator iter = dateList.iterator();
				int endHour = 23;
				Date minDate = null;
				Date maxDate = null;
				while (iter.hasNext()) {
					Object[] obj = (Object[]) iter.next();
					for (int i = 0; i < obj.length; i++) {
						if (i == 0)
							minDate = (Date) obj[i];
						if (i == 1)
							maxDate = (Date) obj[i];

					}
				}

				if (isDashBoardData) {
					if (isTodayDate(startDate) == 0) {
						long diff = 0;
						if (maxDate != null)
							diff = new Date().getTime() - maxDate.getTime();
						else
							diff = new Date().getTime() - startDate.getTime();
						long diffMinutes = diff / (60 * 1000);
						if (diffMinutes < 60) {
							Calendar todayCalendar = Calendar.getInstance();
							todayCalendar.setTime(new Date());
							endHour = todayCalendar.get(Calendar.HOUR_OF_DAY) - 1;
						}
					}
				}

				Calendar endCalendar = Calendar.getInstance();
				endCalendar.setTime(startDate);
				endCalendar.set(Calendar.HOUR_OF_DAY, endHour);
				endCalendar.set(Calendar.MINUTE, 59);
				endCalendar.set(Calendar.SECOND, 00);
				endCalendar.set(Calendar.MILLISECOND, 0);

				Calendar startCalendar = Calendar.getInstance();
				startCalendar.setTime(startDate);
				startCalendar.set(Calendar.HOUR_OF_DAY, 00);
				startCalendar.set(Calendar.MINUTE, 00);
				startCalendar.set(Calendar.SECOND, 00);
				startCalendar.set(Calendar.MILLISECOND, 0);

				criteria.add(Restrictions.ge("ER.readingDate", startCalendar.getTime()));
				criteria.add(Restrictions.le("ER.readingDate", endCalendar.getTime()));
			} else {
				Calendar endCalendar = Calendar.getInstance();
				if (endDate != null) {
					endCalendar.setTime(endDate);
					endCalendar.set(Calendar.HOUR_OF_DAY, 23);
					endCalendar.set(Calendar.MINUTE, 59);
					endCalendar.set(Calendar.SECOND, 00);
					endCalendar.set(Calendar.MILLISECOND, 0);
				}
				Calendar startCalendar = Calendar.getInstance();
				if (startDate != null) {
					startCalendar.setTime(startDate);
					startCalendar.set(Calendar.HOUR_OF_DAY, 00);
					startCalendar.set(Calendar.MINUTE, 00);
					startCalendar.set(Calendar.SECOND, 00);
					startCalendar.set(Calendar.MILLISECOND, 0);
				}

				criteria.add(Restrictions.ge("ER.readingDate", startCalendar.getTime()));
				criteria.add(Restrictions.le("ER.readingDate", endCalendar.getTime()));

			}
			criteria.setProjection(Projections.projectionList().add(Projections.property("ER.readingDate"), "readingDate").add(Projections.property("ER.voltage"), "voltage").add(Projections.property("ER.current"), "current").add(Projections.property("ER.energy"), "energy").add(Projections.property("ER.phase"), "phase"));
			criteria.addOrder(Order.asc("ER.readingDate"));
			list = criteria.setResultTransformer(Transformers.aliasToBean(ReadingDTO.class)).list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		Map chartValueMap = getChartValueMap(list, vType, equipmentType, displayGroupNo, startDate, endDate, isDGConfigured);
		return chartValueMap;
	}

	private int isTodayDate(Date date) {
		Calendar todayCalendar = Calendar.getInstance();
		todayCalendar.setTime(new Date());
		todayCalendar.set(Calendar.HOUR_OF_DAY, 00);
		todayCalendar.set(Calendar.MINUTE, 00);
		todayCalendar.set(Calendar.SECOND, 00);
		todayCalendar.set(Calendar.MILLISECOND, 0);

		Calendar compareCalendar = Calendar.getInstance();
		compareCalendar.setTime(date);
		compareCalendar.set(Calendar.HOUR_OF_DAY, 00);
		compareCalendar.set(Calendar.MINUTE, 00);
		compareCalendar.set(Calendar.SECOND, 00);
		compareCalendar.set(Calendar.MILLISECOND, 0);
		return compareCalendar.compareTo(todayCalendar);
	}

	private Map getChartValueMap(List<ReadingDTO> list, String visualizationType, String equipmentType, String displayGroupNo, Date fromDate, Date toDate, boolean isDGConfigured) {
		Map dataMap = new LinkedHashMap();
		addDefaultValue(dataMap, visualizationType, fromDate, toDate);
		// System.err.println(" dataMap : "+dataMap.toString());
		String previousValue = null;
		Double previousReading = 0.0;
		Double sum = 0.0;
		int index = 0;
		if(list != null){
			for (ReadingDTO readingDTO : list) {
				if (!isDGConfigured || (isDGConfigured && (readingDTO.getPhase() != null && readingDTO.getPhase().equalsIgnoreCase("R")) && (equipmentType.equalsIgnoreCase("Utility") || equipmentType.equalsIgnoreCase("Diesel Generator"))) || (isDGConfigured && (equipmentType.equalsIgnoreCase("Inverter") || equipmentType.equalsIgnoreCase("Battery") || equipmentType.equalsIgnoreCase("Panel")))) {
					if (visualizationType.equalsIgnoreCase("Hourly")) {
						Calendar readingCalendar = Calendar.getInstance();
						readingCalendar.setTime(readingDTO.getReadingDate());

						if (index == 0) {
							previousValue = String.valueOf(readingCalendar.get(Calendar.HOUR_OF_DAY));
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();

						}

						if (!String.valueOf(readingCalendar.get(Calendar.HOUR_OF_DAY)).equalsIgnoreCase(previousValue)) {

							List dataValueList = new ArrayList();
							Double calcValue = 0.0;
							if (!equipmentType.equalsIgnoreCase("Battery"))
								calcValue = Math.round(sum * 100.0) / 100.0;
							else
								calcValue = sum;// -previousReading;
							dataValueList.add(calcValue);

							if (!dataMap.containsKey((Integer.valueOf(previousValue) + 1)))
								dataMap.put(Integer.valueOf(previousValue) + 1, dataValueList);
							else {
								if (dataMap.get((Integer.valueOf(previousValue) + 1)) == null)
									dataMap.put(Integer.valueOf(previousValue) + 1, dataValueList);
							}

							previousValue = String.valueOf(readingCalendar.get(Calendar.HOUR_OF_DAY));
							sum = 0.0;

						} else {
							sum = !equipmentType.equalsIgnoreCase("Battery") ? (sum + (readingDTO.getEnergy() - previousReading)) : readingDTO.getVoltage();
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

					} else if (visualizationType.equalsIgnoreCase("Daily")) {
						Calendar readingCalendar = Calendar.getInstance();
						readingCalendar.setTime(readingDTO.getReadingDate());
						readingCalendar.set(Calendar.HOUR, 00);
						readingCalendar.set(Calendar.MINUTE, 00);
						readingCalendar.set(Calendar.SECOND, 00);
						readingCalendar.set(Calendar.MILLISECOND, 0);

						if (index == 0) {

							previousValue = new SimpleDateFormat("dd/MM/yyyy").format(readingCalendar.getTime());
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

						if (previousValue != null && !new SimpleDateFormat("dd/MM/yyyy").format(readingCalendar.getTime()).equalsIgnoreCase(previousValue)) {
							List dataValueList = new ArrayList();
							Double calcValue = 0.0;
							if (!equipmentType.equalsIgnoreCase("Battery"))
								calcValue = Math.round(sum * 100.0) / 100.0;
							else
								calcValue = sum;// -previousReading;
							dataValueList.add(calcValue);
							if (!dataMap.containsKey(previousValue))
								dataMap.put(previousValue, dataValueList);
							else {
								if (dataMap.get(previousValue) == null)
									dataMap.put(previousValue, dataValueList);
							}
							previousValue = new SimpleDateFormat("dd/MM/yyyy").format(readingCalendar.getTime());
							sum = 0.0;
							// previousReading =
							// !equipmentType.equalsIgnoreCase("Battery") ?
							// readingDTO.getEnergy() : readingDTO.getVoltage();
						} else {
							sum = !equipmentType.equalsIgnoreCase("Battery") ? (sum + (readingDTO.getEnergy() - previousReading)) : readingDTO.getVoltage();
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

					} else if (visualizationType.equalsIgnoreCase("Monthly")) {
						Calendar readingCalendar = Calendar.getInstance();
						readingCalendar.setTime(readingDTO.getReadingDate());
						readingCalendar.set(Calendar.HOUR, 00);
						readingCalendar.set(Calendar.MINUTE, 00);
						readingCalendar.set(Calendar.SECOND, 00);
						readingCalendar.set(Calendar.MILLISECOND, 0);

						if (index == 0) {
							previousValue = new SimpleDateFormat("MMM-yyyy").format(readingCalendar.getTime());
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

						if (previousValue != null && !(new SimpleDateFormat("MMM-yyyy").format(readingCalendar.getTime())).equalsIgnoreCase(previousValue)) {
							List dataValueList = new ArrayList();
							Double calcValue = 0.0;
							if (!equipmentType.equalsIgnoreCase("Battery"))
								calcValue = Math.round(sum * 100.0) / 100.0;
							else
								calcValue = sum;// -previousReading;
							dataValueList.add(calcValue);
							if (!dataMap.containsKey(previousValue))
								dataMap.put(previousValue, dataValueList);
							else {
								if (dataMap.get(previousValue) == null)
									dataMap.put(previousValue, dataValueList);
							}
							previousValue = new SimpleDateFormat("MMM-yyyy").format(readingCalendar.getTime());
							sum = 0.0;
							// previousReading =
							// !equipmentType.equalsIgnoreCase("Battery") ?
							// readingDTO.getEnergy() : readingDTO.getVoltage();
						} else {
							sum = !equipmentType.equalsIgnoreCase("Battery") ? (sum + (readingDTO.getEnergy() - previousReading)) : readingDTO.getVoltage();
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

					} else if (visualizationType.equalsIgnoreCase("Yearly")) {
						Calendar readingCalendar = Calendar.getInstance();
						readingCalendar.setTime(readingDTO.getReadingDate());
						readingCalendar.set(Calendar.HOUR, 00);
						readingCalendar.set(Calendar.MINUTE, 00);
						readingCalendar.set(Calendar.SECOND, 00);
						readingCalendar.set(Calendar.MILLISECOND, 0);

						if (index == 0) {
							previousValue = String.valueOf(readingCalendar.get(Calendar.YEAR));
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

						if (previousValue != null && !(String.valueOf(readingCalendar.get(Calendar.YEAR))).equalsIgnoreCase(previousValue)) {
							List dataValueList = new ArrayList();
							Double calcValue = 0.0;
							if (!equipmentType.equalsIgnoreCase("Battery"))
								calcValue = Math.round(sum * 100.0) / 100.0;
							else
								calcValue = sum;// -previousReading;
							dataValueList.add(calcValue);
							if (!dataMap.containsKey(Integer.valueOf(previousValue)))
								dataMap.put(Integer.valueOf(previousValue), dataValueList);
							else {
								if (dataMap.get(previousValue) == null)
									dataMap.put(previousValue, dataValueList);
							}
							previousValue = String.valueOf(readingCalendar.get(Calendar.YEAR));
							sum = 0.0;
							// previousReading =
							// !equipmentType.equalsIgnoreCase("Battery") ?
							// readingDTO.getEnergy() : readingDTO.getVoltage();
						} else {
							sum = !equipmentType.equalsIgnoreCase("Battery") ? (sum + (readingDTO.getEnergy() - previousReading)) : readingDTO.getVoltage();
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
						}

					} else if (visualizationType.equalsIgnoreCase("All")) {

						if (index == 0) {
							previousReading = !equipmentType.equalsIgnoreCase("Battery") ? readingDTO.getEnergy() : readingDTO.getVoltage();
							previousValue = displayGroupNo;
							// System.err.println("previous reading : " +
							// previousReading);
						}

					}

					if (index == list.size() - 1) {
						List dataValueList = new ArrayList();
						Double calcValue = 0.0;
						if (!equipmentType.equalsIgnoreCase("Battery"))
							calcValue = Math.round(sum * 100.0) / 100.0;
						else
							calcValue = sum;// -previousReading;
						dataValueList.add(calcValue);
						if (visualizationType.equalsIgnoreCase("Hourly")) {
							if (!dataMap.containsKey(Integer.valueOf(previousValue) + 1))
								dataMap.put(Integer.valueOf(previousValue) + 1, dataValueList);
							else {
								if (dataMap.get(Integer.valueOf(previousValue) + 1) == null)
									dataMap.put(Integer.valueOf(previousValue) + 1, dataValueList);
							}
						} else if (visualizationType.equalsIgnoreCase("Yearly")) {
							if (!dataMap.containsKey(Integer.valueOf(previousValue)))
								dataMap.put(Integer.valueOf(previousValue), dataValueList);
							else {
								if (dataMap.get(Integer.valueOf(previousValue)) == null)
									dataMap.put(Integer.valueOf(previousValue), dataValueList);
							}

						} else {
							if (!dataMap.containsKey(previousValue))
								dataMap.put(previousValue, dataValueList);
							else {
								if (dataMap.get(previousValue) == null)
									dataMap.put(previousValue, dataValueList);
							}
						}

					}
				}
				index++;
			}
		}
		
		return dataMap;
	}

	private void addDefaultValue(Map dataMap, String visualizationType, Date fromDate, Date toDate) {
		if (visualizationType.equalsIgnoreCase("Hourly")) {
			for (int index = 1; index <= 24; index++) {
				dataMap.put(index, null);
			}
		}

		Calendar startCalendar = Calendar.getInstance();
		if (fromDate != null)
			startCalendar.setTime(fromDate);

		Calendar endCalendar = Calendar.getInstance();
		if (toDate != null)
			endCalendar.setTime(toDate);

		if (visualizationType.equalsIgnoreCase("Daily")) {
			while (startCalendar.before(endCalendar)) {
				dataMap.put(new SimpleDateFormat("dd/MM/yyyy").format(startCalendar.getTime()), null);
				startCalendar.add(Calendar.DATE, 1);
			}
		}

		if (visualizationType.equalsIgnoreCase("Monthly")) {

			while (startCalendar.before(endCalendar)) {
				dataMap.put(new SimpleDateFormat("MMM-yyyy").format(startCalendar.getTime()), null);
				startCalendar.add(Calendar.MONTH, 1);
			}
		}

		if (visualizationType.equalsIgnoreCase("Monthly")) {

			while (startCalendar.before(endCalendar)) {
				dataMap.put(startCalendar.get(Calendar.YEAR), null);
				startCalendar.add(Calendar.YEAR, 1);
			}
		}

	}

	private List<ParameterDTO> getGaugeConfiguration(Long siteId, String displayGroupNo, String equipmentType) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List<ParameterDTO> list = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(Site.class, "S");
			criteria.createAlias("S.equipments", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");
			criteria.createAlias("C.parameters", "P");
			if (siteId != null)
				criteria.add(Restrictions.eq("S.id", siteId));
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.add(Restrictions.eq("ET.name", equipmentType));

			criteria.setProjection(Projections.projectionList().add(Projections.property("P.id"), "id").add(Projections.property("P.startRange"), "start").add(Projections.property("P.endRange"), "end").add(Projections.property("P.minYellowRange"), "minYellow").add(Projections.property("P.maxYellowRange"), "maxYellow").add(Projections.property("P.minGreenRange"), "minGreen").add(Projections.property("P.maxGreenRange"), "maxGreen").add(Projections.property("P.minRedRange"), "minRed").add(Projections.property("P.maxRedRange"), "maxRed").add(Projections.property("P.type"), "type"));

			list = criteria.setResultTransformer(Transformers.aliasToBean(ParameterDTO.class)).list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return list;

	}

	public String getInverterType(String displayGroupNo) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List<PartySiteDTO> list = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(Equipment.class, "E");
			criteria.createAlias("E.site", "S");
			criteria.createAlias("S.invertorType", "I");

			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));

			criteria.setProjection(Projections.projectionList().add(Projections.property("I.name"), "inverterType")

			);

			list = criteria.setResultTransformer(Transformers.aliasToBean(PartySiteDTO.class)).list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return list.get(0).getInverterType();

	}

	private List<ReadingDTO> getGaugeReading(Long siteId, String displayGroupNo, String equipmentType, String phase) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		if (phase != null) {
			if (phase.equalsIgnoreCase("Phase I"))
				phase = "R";
			if (phase.equalsIgnoreCase("Phase II"))
				phase = "Y";
			if (phase.equalsIgnoreCase("Phase III"))
				phase = "B";
		}
		List<ReadingDTO> list = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria equipmentCountCriteria = session.createCriteria(Equipment.class, "E");
			equipmentCountCriteria.createAlias("E.site", "S");

			if (siteId != null)
				equipmentCountCriteria.add(Restrictions.eq("S.id", siteId));
			equipmentCountCriteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));

			equipmentCountCriteria.setProjection(Projections.projectionList().add(Projections.count("E.id")));

			List equipmentCountList = equipmentCountCriteria.list();
			Iterator iterator = equipmentCountList.iterator();
			Long equipmentCount = (Long) iterator.next();
			// System.err.println("count : " + equipmentCount);
			Criteria criteria = session.createCriteria(Site.class, "S");
			criteria.createAlias("S.equipments", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");
			criteria.createAlias("E.equipmentReadings", "ER");
			if (siteId != null)
				criteria.add(Restrictions.eq("S.id", siteId));
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			if (!equipmentType.equalsIgnoreCase("All"))
				criteria.add(Restrictions.eq("ET.name", equipmentType));

			if (phase != null)
				criteria.add(Restrictions.eq("ER.phase", phase));
			criteria.setProjection(Projections.projectionList().add(Projections.property("ER.readingDate"), "readingDate").add(Projections.property("ER.voltage"), "voltage").add(Projections.property("ER.current"), "current").add(Projections.property("ER.energy"), "energy").add(Projections.property("ET.name"), "equipmentType").add(Projections.property("ER.power"), "power"));
			criteria.addOrder(Order.desc("ER.id"));
			criteria.setMaxResults(equipmentCount.intValue());

			list = criteria.setResultTransformer(Transformers.aliasToBean(ReadingDTO.class)).list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return list;

	}

	public List getSites(Long partyId) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		List dataList = new ArrayList();
		Session session = hibernateServiceImpl.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(PartySiteRelation.class, "PSR");
			criteria.createAlias("PSR.site", "S");
			criteria.createAlias("S.equipments", "E");
			criteria.createAlias("S.invertorType", "I");
			if (partyId != null) {
				criteria.createAlias("PSR.party", "P");
				criteria.add(Restrictions.eq("P.id", partyId));
			}
			criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("S.id"), "siteId").add(Projections.property("S.location"), "location").add(Projections.property("E.displayGroupNo"), "siteGroupNumber").add(Projections.property("S.name"), "siteName").add(Projections.property("I.name"), "inverterType")));

			List<PartySiteDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(PartySiteDTO.class)).list();
			tx.commit();
			for (PartySiteDTO partySiteDTO : list) {
				List<Object> dataValueList = new ArrayList<Object>();
				dataValueList.add(partySiteDTO.getSiteId());
				dataValueList.add(partySiteDTO.getSiteGroupNumber());
				dataValueList.add(partySiteDTO.getLocation());
				dataValueList.add(partySiteDTO.getSiteName());
				dataValueList.add(partySiteDTO.getInverterType());
				dataList.add(dataValueList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataList;
	}

	public Map getSiteLiveData(Long siteId, String displayGroupNo) {

		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		Map dataMap = new HashMap();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			// session.flush();
			Criteria criteria = session.createCriteria(Site.class, "S");
			criteria.add(Restrictions.eq("S.id", siteId));
			List<Site> siteList = criteria.list();
			List dataList = new ArrayList();
			List readingDataList = new ArrayList();
			List<ReadingDTO> readingList = getGaugeReading(siteId, displayGroupNo, "All", null);
			for (ReadingDTO readingDTO : readingList) {
				ArrayList dataValueList = new ArrayList();
				dataValueList.add(readingDTO.getReadingDate());
				dataValueList.add(readingDTO.getVoltage());
				dataValueList.add(readingDTO.getCurrent());
				dataValueList.add(readingDTO.getEnergy());
				dataValueList.add(readingDTO.getEquipmentType());
				dataValueList.add(readingDTO.getPower());
				readingDataList.add(dataValueList);
			}
			Site site = (Site) siteList.get(0);
			String inverterName = site.getInvertorType().getName();
			// System.err.println("dataValueList" + dataList.toString());
			dataList.add(readingDataList);
			criteria = session.createCriteria(Equipment.class, "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.setProjection(Projections.projectionList().add(Projections.property("ET.name"), "equipmentType").add(Projections.property("E.capacity"), "capacity"));
			criteria.setResultTransformer(Transformers.aliasToBean(EquipmentDTO.class)).list();
			List<EquipmentDTO> capacityList = criteria.list();
			List capacityDataList = new ArrayList();
			for (EquipmentDTO equipmentDTO : capacityList) {
				List dataValueList = new ArrayList();
				dataValueList.add(equipmentDTO.getEquipmentType());
				dataValueList.add(equipmentDTO.getCapacity());
				capacityDataList.add(dataValueList);
			}

			dataList.add(capacityDataList);
			dataMap.put(inverterName, dataList);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataMap;
	}

	public List getTodayUsage(Long siteId, String displayGroupNo, boolean isDGConfigured) {

		Map panelMap = getDataMapByGroupNo(siteId, displayGroupNo, "Panel", "Daily", new Date(), new Date(), isDGConfigured, false);
		Map utilityMap = getDataMapByGroupNo(siteId, displayGroupNo, "Utility", "Daily", new Date(), new Date(), isDGConfigured, false);
		Map inverterMap = getDataMapByGroupNo(siteId, displayGroupNo, "Inverter", "Daily", new Date(), new Date(), isDGConfigured, false);
		// System.err.println("utilityMap : "+utilityMap.toString());
		// System.err.println("inverterMap : "+inverterMap.toString());
		Double solarGenValue = 0.0;
		Double consumedPower = 0.0;
		Double importedPower = 0.0;
		Set set = panelMap.entrySet();
		Iterator i = set.iterator();
		while (i.hasNext()) {
			Map.Entry me = (Map.Entry) i.next();
			String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
			ArrayList dataValueList = (ArrayList) me.getValue();
			solarGenValue = (Double) dataValueList.get(0);
		}

		set = inverterMap.entrySet();
		i = set.iterator();
		while (i.hasNext()) {
			Map.Entry me = (Map.Entry) i.next();
			String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
			ArrayList dataValueList = (ArrayList) me.getValue();
			consumedPower = (Double) dataValueList.get(0);
		}

		set = utilityMap.entrySet();
		i = set.iterator();
		while (i.hasNext()) {
			Map.Entry me = (Map.Entry) i.next();
			String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
			ArrayList dataValueList = (ArrayList) me.getValue();
			importedPower = dataValueList != null ? (Double) dataValueList.get(0) : 0.0;
		}
		System.err.println(" solarGenValue: " + solarGenValue + " consumedPower  " + consumedPower + "importedPower : " + importedPower);
		List dataList = new ArrayList();
		dataList.add(solarGenValue);
		dataList.add(consumedPower);
		dataList.add(importedPower);
		// return chartValueMap;
		return dataList;
	}

	public List getGreenHouseData(Long siteId, String displayGroupNo, boolean isDGConfigured) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List<Double> dataValueList = new ArrayList();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria maxReadingDateCriteria = session.createCriteria(Site.class, "S");
			maxReadingDateCriteria.createAlias("S.equipments", "E");
			maxReadingDateCriteria.createAlias("E.configuration", "C");
			maxReadingDateCriteria.createAlias("E.equipmentReadings", "ER");
			if (siteId != null)
				maxReadingDateCriteria.add(Restrictions.eq("S.id", siteId));
			maxReadingDateCriteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));

			maxReadingDateCriteria.setProjection(Projections.projectionList().add(Projections.min("ER.readingDate")).add(Projections.max("ER.readingDate")));
			List list = maxReadingDateCriteria.list();
			tx.commit();

			Iterator iter = list.iterator();
			Date minDate = null;
			Date maxDate = null;
			while (iter.hasNext()) {
				Object[] obj = (Object[]) iter.next();
				for (int i = 0; i < obj.length; i++) {
					if (i == 0)
						minDate = (Date) obj[i];
					if (i == 1)
						maxDate = (Date) obj[i];

				}
			}

			if (displayGroupNo != null) {
				Map panelMap = getDataMapByGroupNo(siteId, displayGroupNo, "Panel", "All", minDate, maxDate, isDGConfigured, false);
				Map utilityMap = getDataMapByGroupNo(siteId, displayGroupNo, "Utility", "All", minDate, maxDate, isDGConfigured, false);
				ArrayList<Double> panelList = (ArrayList<Double>) panelMap.get(displayGroupNo);
				Double solarProd = panelList != null ? panelList.get(0) : 0.0;

				// Double inverterProd =
				// ((ArrayList<Double>)utilityMap.get(displayGroupNo)).get(0);
				Double netProd = solarProd;
				Double co2 = (netProd * 0.940) / 2.20462;
				Double so2 = (netProd * 3.840) / 2.20462;
				Double no2 = (netProd * 0.00434) / 2.20462;
				dataValueList.add(Math.round(co2 * 100.0) / 100.0);
				dataValueList.add(Math.round(so2 * 100.0) / 100.0);
				dataValueList.add(Math.round(no2 * 100.0) / 100.0);
				System.err.println("dataValueList " + dataValueList.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataValueList;
	}

	public List getSiteBydisplayGroupNo(String displayGroupNo) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List dataList = new ArrayList();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(Equipment.class, "E");

			criteria.createAlias("E.site", "S");
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("S.id"), "siteId").add(Projections.property("S.name"), "siteName")));
			List<PartySiteDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(PartySiteDTO.class)).list();
			tx.commit();
			PartySiteDTO partySiteDTO = list.get(0);
			dataList.add(partySiteDTO.getSiteId());
			dataList.add(partySiteDTO.getSiteName());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return dataList;
	}

	public Map getSummaryData(Long siteId, String displayGroupNo, boolean isDGConfigured) {
		Map<String, List> dataMap = new LinkedHashMap<String, List>();
		Date startDate = new Date();
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.setTime(startDate);
		startCalendar.set(Calendar.HOUR_OF_DAY, 00);
		startCalendar.set(Calendar.MINUTE, 00);
		startCalendar.set(Calendar.SECOND, 00);
		startCalendar.set(Calendar.MILLISECOND, 0);

		Calendar endCalendar = Calendar.getInstance();
		endCalendar.setTime(startDate);
		endCalendar.set(Calendar.HOUR_OF_DAY, 23);
		endCalendar.set(Calendar.MINUTE, 59);
		endCalendar.set(Calendar.SECOND, 00);
		endCalendar.set(Calendar.MILLISECOND, 0);

		// System.err.println("Today : startDate : "+startCalendar.getTime() +
		// " endDate : "+endCalendar.getTime());
		List conList = new ArrayList();
		List<List> dataList = getReportData(siteId, displayGroupNo, "Daily", startCalendar.getTime(), endCalendar.getTime(), isDGConfigured);
		dataList.remove(0);
		Double sumPanel = 0.0;
		Double sumInverter = 0.0;
		Double sumUtility = 0.0;
		for (List dataValueList : dataList) {
			sumPanel = sumPanel + (Double) dataValueList.get(1);
			sumInverter = sumInverter + (Double) dataValueList.get(2);
			sumUtility = sumUtility + (Double) dataValueList.get(3);
		}

		conList = new ArrayList();
		conList.add(Math.round(sumPanel * 100.0) / 100.0);
		conList.add(Math.round(sumInverter * 100.0) / 100.0);
		conList.add(Math.round(sumUtility * 100.0) / 100.0);

		dataMap.put("Today", conList);
		sumPanel = 0.0;
		sumInverter = 0.0;
		sumUtility = 0.0;

		int dayOfTheWeek = endCalendar.get(Calendar.DAY_OF_WEEK);
		startCalendar = Calendar.getInstance();
		startCalendar.setTime(endCalendar.getTime());
		startCalendar.set(Calendar.HOUR_OF_DAY, 00);
		startCalendar.set(Calendar.MINUTE, 00);
		startCalendar.set(Calendar.SECOND, 00);
		startCalendar.set(Calendar.MILLISECOND, 0);
		startCalendar.add(Calendar.DAY_OF_MONTH, -(dayOfTheWeek - 1));

		// System.err.println("This Week : startDate : "+startCalendar.getTime()
		// + " endDate : "+endCalendar.getTime());

		dataList = getReportData(siteId, displayGroupNo, "Daily", startCalendar.getTime(), endCalendar.getTime(), isDGConfigured);
		dataList.remove(0);
		for (List dataValueList : dataList) {
			sumPanel = sumPanel + (Double) dataValueList.get(1);
			sumInverter = sumInverter + (Double) dataValueList.get(2);
			sumUtility = sumUtility + (Double) dataValueList.get(3);
		}

		conList = new ArrayList();
		conList.add(Math.round(sumPanel * 100.0) / 100.0);
		conList.add(Math.round(sumInverter * 100.0) / 100.0);
		conList.add(Math.round(sumUtility * 100.0) / 100.0);
		dataMap.put("Week", conList);

		sumPanel = 0.0;
		sumInverter = 0.0;
		sumUtility = 0.0;
		int dayOfTheMonth = endCalendar.get(Calendar.DAY_OF_MONTH);
		startCalendar = Calendar.getInstance();
		startCalendar.setTime(endCalendar.getTime());
		startCalendar.set(Calendar.HOUR_OF_DAY, 00);
		startCalendar.set(Calendar.MINUTE, 00);
		startCalendar.set(Calendar.SECOND, 00);
		startCalendar.set(Calendar.MILLISECOND, 0);
		startCalendar.add(Calendar.DAY_OF_MONTH, -(dayOfTheMonth - 1));

		// System.err.println("This Month : startDate : "+startCalendar.getTime()
		// + " endDate : "+endCalendar.getTime());

		dataList = getReportData(siteId, displayGroupNo, "Daily", startCalendar.getTime(), endCalendar.getTime(), isDGConfigured);
		dataList.remove(0);
		for (List dataValueList : dataList) {
			sumPanel = sumPanel + (Double) dataValueList.get(1);
			sumInverter = sumInverter + (Double) dataValueList.get(2);
			sumUtility = sumUtility + (Double) dataValueList.get(3);
		}

		conList = new ArrayList();
		conList.add(Math.round(sumPanel * 100.0) / 100.0);
		conList.add(Math.round(sumInverter * 100.0) / 100.0);
		conList.add(Math.round(sumUtility * 100.0) / 100.0);

		dataMap.put("Month", conList);

		sumPanel = 0.0;
		sumInverter = 0.0;
		sumUtility = 0.0;

		int dayOfTheYear = endCalendar.get(Calendar.DAY_OF_YEAR);
		startCalendar = Calendar.getInstance();
		startCalendar.setTime(endCalendar.getTime());
		startCalendar.set(Calendar.HOUR_OF_DAY, 00);
		startCalendar.set(Calendar.MINUTE, 00);
		startCalendar.set(Calendar.SECOND, 00);
		startCalendar.set(Calendar.MILLISECOND, 0);
		startCalendar.add(Calendar.DAY_OF_MONTH, -(dayOfTheYear - 1));

		// System.err.println("This Year : startDate : "+startCalendar.getTime()
		// + " endDate : "+endCalendar.getTime());
		dataList = getReportData(siteId, displayGroupNo, "Daily", startCalendar.getTime(), endCalendar.getTime(), isDGConfigured);
		dataList.remove(0);
		for (List dataValueList : dataList) {
			sumPanel = sumPanel + (Double) dataValueList.get(1);
			sumInverter = sumInverter + (Double) dataValueList.get(2);
			sumUtility = sumUtility + (Double) dataValueList.get(3);
		}

		conList = new ArrayList();
		conList.add(Math.round(sumPanel * 100.0) / 100.0);
		conList.add(Math.round(sumInverter * 100.0) / 100.0);
		conList.add(Math.round(sumUtility * 100.0) / 100.0);
		dataMap.put("Year", conList);

		// System.err.println(dataMap.toString());
		return dataMap;
	}

	public String generateReportToken(ReportBean reportBean) {
		String token = "";
		if (reportBean.getDocType().equalsIgnoreCase("excel")) {
			List dataList = getReportData(reportBean.getSiteId(), reportBean.getDisplayGroupNo(), reportBean.getvType(), reportBean.getStartDate(), reportBean.getEndDate(), reportBean.isDGConfigured());
			final List headingList = (List) dataList.get(0);
			dataList.remove(0);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ExcelReportGenerator excelReport = new ExcelReportGenerator();
			try {
				excelReport.createWorkBook(headingList, dataList, baos);
				byte[] byteArray = baos.toByteArray();
				token = token + new Date().getTime();
				HttpServletRequest request = this.getThreadLocalRequest();
				HttpSession session = request.getSession();
				session.setAttribute(token, byteArray);

			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return token;
	}

	public static void main(String[] args) {
		MeterServiceImpl meterServiceImpl = new MeterServiceImpl();
/*		ReportBean reportBean = new ReportBean();
		reportBean.setDocType("excel");
		reportBean.setvType("Hourly");
		reportBean.setSiteId(1L);
		reportBean.setDGConfigured(false);
		reportBean.setDisplayGroupNo("295 - 296");
		Calendar startCalendar = Calendar.getInstance();
		startCalendar.set(Calendar.DATE, 10);
		startCalendar.set(Calendar.MONTH, 7);
		startCalendar.set(Calendar.YEAR, 2013);
		startCalendar.set(Calendar.HOUR_OF_DAY, 00);
		startCalendar.set(Calendar.MINUTE, 00);
		startCalendar.set(Calendar.SECOND, 00);
		startCalendar.set(Calendar.MILLISECOND, 0);

		Calendar endCalendar = Calendar.getInstance();
		endCalendar.set(Calendar.DATE, 10);
		endCalendar.set(Calendar.MONTH, 7);
		endCalendar.set(Calendar.YEAR, 2013);
		endCalendar.set(Calendar.HOUR_OF_DAY, 23);
		endCalendar.set(Calendar.MINUTE, 59);
		endCalendar.set(Calendar.SECOND, 00);
		endCalendar.set(Calendar.MILLISECOND, 0);

		System.err.println("start date : " + startCalendar.getTime());
		System.err.println("end date : " + endCalendar.getTime());
		reportBean.setStartDate(startCalendar.getTime());
		reportBean.setStartDate(endCalendar.getTime());*/
		List headingList = new ArrayList();
		headingList.add("15/09/2013");
		headingList.add("10:15:00");
		headingList.add(102.0);
		headingList.add(103.5);
		headingList.add(124.6);
		headingList.add(123.6);
		headingList.add(624.0);
		headingList.add(525.9);
		headingList.add("EB");
		headingList.add(311.6);
		System.err.println("heading list initial "+headingList.toString());
		headingList.remove(0);
		System.err.println("heading list first "+headingList.toString());
		headingList.remove(0);
		System.err.println("heading list second "+headingList.toString());

		Double mins = 60.00;
		System.err.println("Hours "+ Math.floor(mins/60));
		System.err.println("Mins "+ mins%60);
		
		// List datamap = meterServiceImpl.getSummaryData(1L, "295 - 296");
		// System.err.println("dataMap : "+datamap.toString());
	}
	public List getEquipmentRunningHours(String displayGroupNo){
		List dataList = new ArrayList ();
		List<ReadingDTO> todayRunningList = getRunningMins(displayGroupNo, true, false);
		List todayDataValueList = new ArrayList();
		if(todayRunningList.size() == 0){
			todayDataValueList.add(0);
			todayDataValueList.add(0);
			dataList.add(todayDataValueList);
		}else if(todayRunningList.size() > 0){
			ReadingDTO todayReading  = todayRunningList.get(0);
			Double todayCumRunMins =	todayReading.getRunningMins() != null ?  todayReading.getRunningMins() : 0.0;
			System.err.println("todayCumRunMins : "+todayCumRunMins);
			if(todayCumRunMins > 0){
				List<ReadingDTO> previousRunningList = getRunningMins(displayGroupNo, false, true);
				Double previousCumRunMins = 0.0;
				ReadingDTO previousReading = previousRunningList.size() > 0 ? previousRunningList.get(0) : null;
				if(previousReading != null)
					previousCumRunMins = previousReading.getRunningMins() != null ? previousReading.getRunningMins() : 0.0;
				
				System.err.println("previousCumRunMins : "+previousCumRunMins);
				Double todayRunningMins = todayCumRunMins - previousCumRunMins;
				todayDataValueList.add((int)Math.floor(todayRunningMins/60));
				todayDataValueList.add((int)(todayRunningMins%60));
				dataList.add(todayDataValueList);
			}else{
				todayDataValueList.add(0);
				todayDataValueList.add(0);
				dataList.add(todayDataValueList);
			}
		}
		List<ReadingDTO> totalRunningList = getRunningMins(displayGroupNo, false, false);
		List totalDataValueList = new ArrayList();
		if(totalRunningList.size() == 0){
			totalDataValueList.add(0);
			totalDataValueList.add(0);
			dataList.add(totalDataValueList);
		}else if(totalRunningList.size() >0){
			ReadingDTO totalReading  = totalRunningList.get(0);
			Double totalCumRunMins =	totalReading.getRunningMins() != null ? totalReading.getRunningMins() : 0.0;
			if(totalCumRunMins > 0){
				totalDataValueList.add((int)Math.floor(totalCumRunMins/60));
				totalDataValueList.add((int)(totalCumRunMins%60));
				dataList.add(totalDataValueList);
			}else{
				totalDataValueList.add(0);
				totalDataValueList.add(0);
				dataList.add(totalDataValueList);
			}
		}
		
		return dataList;
	}
	
	public List<ReadingDTO> getRunningMins(String displayGroupNo, boolean isTodayRunning,boolean isPreviousClosing) {
		HibernateServiceImpl hibernateServiceImpl = new HibernateServiceImpl();
		Session session = hibernateServiceImpl.getSession();
		List dataList = new ArrayList();
		Transaction tx = null;
		List<ReadingDTO> list = null;
		try {
			Calendar todayCalendar = Calendar.getInstance();
			todayCalendar.setTime(new Date());
			todayCalendar.set(Calendar.HOUR_OF_DAY, 00);
			todayCalendar.set(Calendar.MINUTE, 00);
			todayCalendar.set(Calendar.SECOND, 00);
			todayCalendar.set(Calendar.MILLISECOND, 0);


			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(EquipmentReading.class, "ER");
			criteria.createAlias("ER.equipment", "E");
			criteria.createAlias("E.configuration", "C");
			criteria.createAlias("C.equipmentType", "ET");
			criteria.add(Restrictions.eq("E.displayGroupNo", displayGroupNo));
			criteria.add(Restrictions.eq("ET.name","Diesel Generator"));
			criteria.add(Restrictions.eq("ER.phase","R"));
			if(isPreviousClosing)
				criteria.add(Restrictions.lt("ER.readingDate", todayCalendar.getTime()));
			if(isTodayRunning)
				criteria.add(Restrictions.gt("ER.readingDate", todayCalendar.getTime()));
			criteria.addOrder(Order.desc("ER.readingDate"));
			criteria.setMaxResults(1);
			criteria.setProjection(Projections.distinct(Projections.projectionList()
					.add(Projections.property("ER.runningMins"), "runningMins")));
			list = criteria.setResultTransformer(Transformers.aliasToBean(ReadingDTO.class)).list();
			System.err.println(list.toString());
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return list;
	}
}
